package hczc.longcai.com.hccrowdfunding.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import hczc.longcai.com.hccrowdfunding.R;
import hczc.longcai.com.hccrowdfunding.activity.BaseActivity;
import hczc.longcai.com.hccrowdfunding.activity.LoginActivity;
import hczc.longcai.com.hccrowdfunding.application.BaseApplication;
import hczc.longcai.com.hccrowdfunding.home.first_index.FirstFragment;
import hczc.longcai.com.hccrowdfunding.home.fourth_mine.FourthFragment;
import hczc.longcai.com.hccrowdfunding.home.second_invest.SecondFragment;
import hczc.longcai.com.hccrowdfunding.home.third_rankinglist.ThirdFragment;
import hczc.longcai.com.hccrowdfunding.search.SearchActivity;

/**
 * 主页面
 */
public class HomeActivity extends BaseActivity implements View.OnClickListener {


    private static final String TAG = "HomeActivity";

    private long exitTime = 0;

    private ImageView foot_first_pic;
    private ImageView foot_second_pic;
    private ImageView foot_third_pic;
    private ImageView foot_fourth_pic;

    private RelativeLayout first_index;
    private RelativeLayout second_index;
    private RelativeLayout third_index;
    private RelativeLayout fourth_index;

    private FirstFragment firstFragment;
    private SecondFragment secondFragment;
    private ThirdFragment thirdFragment;
    private FourthFragment fourthFragment;

    private FragmentManager manager;
    private View search;
    private TextView title;
    private ImageView logo;

    private List<ImageView> foots;
    private List<TextView> foot_texts;

    private TextView foot_first_text;
    private TextView foot_second_text;
    private TextView foot_third_text;
    private TextView foot_fourth_text;

    private SharedPreferences mSharedPreferences;

    private ChangeReceiver receiver;

    private ChangeLable changeLable;


    public interface ChangeLable {
        public void changeLable(int i);
    }

    public void setChangeLable(ChangeLable changeLable) {
        this.changeLable = changeLable;
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            clickSecond();
            int obj = (int) msg.obj;
            if (changeLable != null) {
                changeLable.changeLable(obj);
            } else {
                Bundle bundle = new Bundle();
                bundle.putInt("lable", obj);
                secondFragment.setArguments(bundle);
            }
//            Log.d(TAG, "*************" + obj + "****************");

        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        mSharedPreferences = BaseApplication.mSharedPreferences;

        initViews();
//        getPics();
        initFragments();

    }

    @Override
    protected void onResume() {
        super.onResume();
        receiver = new ChangeReceiver();
        IntentFilter filter = new IntentFilter("change");
        registerReceiver(receiver, filter);
    }

    /**
     * 初始化4个选项卡Fragment
     */
    private void initFragments() {

        manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        firstFragment = new FirstFragment();
        transaction.add(R.id.fragment_framelayout, firstFragment);
        transaction.commit();

    }

    /**
     * 获取处理过的4个导航按钮图片（没用上）
     */

//    private void getPics() {
//        int height = 70;
//        int width = 70;
//        Log.d(TAG, "控件高度：" + height + "控件宽度：" + width);
//        Resources resources = getResources();
//        Bitmap first_bitmap = BitmapUtils.getCompBitmap(resources, R.drawable.u58, width, height);
//        foot_first_pic.setImageBitmap(first_bitmap);
//        foot_second_pic.setImageBitmap(BitmapUtils.getCompBitmap(resources, R.drawable.u60, width, height));
//        foot_third_pic.setImageBitmap(BitmapUtils.getCompBitmap(resources, R.drawable.u64, width, height));
//        foot_fourth_pic.setImageBitmap(BitmapUtils.getCompBitmap(resources, R.drawable.u62, width, height));
//    }

    /**
     * 初始化视图
     */

    private void initViews() {

        initHeadViews();
        initFootViews();

    }

    /**
     * 初始化头视图，即标题
     */
    private void initHeadViews() {
        title = ((TextView) findViewById(R.id.home_head_title));
        title.setVisibility(View.GONE);
        logo = ((ImageView) findViewById(R.id.home_head_logo));
        logo.setVisibility(View.VISIBLE);
        search = findViewById(R.id.home_head_search);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(HomeActivity.this, SearchActivity.class));

            }
        });
    }

    /**
     * 初始化底部视图，即四个选项卡按钮
     */
    private void initFootViews() {

        foots = new ArrayList<>();
        foot_texts = new ArrayList<>();

        foot_first_pic = ((ImageView) findViewById(R.id.foot_first_pic));
        foot_first_pic.setSelected(true);
        foots.add(foot_first_pic);
        foot_second_pic = ((ImageView) findViewById(R.id.foot_second_pic));
        foots.add(foot_second_pic);
        foot_third_pic = ((ImageView) findViewById(R.id.foot_third_pic));
        foots.add(foot_third_pic);
        foot_fourth_pic = ((ImageView) findViewById(R.id.foot_fourth_pic));
        foots.add(foot_fourth_pic);

        first_index = ((RelativeLayout) findViewById(R.id.foot_first_index));
        second_index = ((RelativeLayout) findViewById(R.id.foot_second_index));
        third_index = ((RelativeLayout) findViewById(R.id.foot_third_index));
        fourth_index = ((RelativeLayout) findViewById(R.id.foot_fourth_index));

        foot_first_text = ((TextView) findViewById(R.id.foot_first_text));
        foot_first_text.setTextColor(Color.parseColor("#e9a150"));
        foot_texts.add(foot_first_text);
        foot_second_text = ((TextView) findViewById(R.id.foot_second_text));
        foot_texts.add(foot_second_text);
        foot_third_text = ((TextView) findViewById(R.id.foot_third_text));
        foot_texts.add(foot_third_text);
        foot_fourth_text = ((TextView) findViewById(R.id.foot_fourth_text));
        foot_texts.add(foot_fourth_text);

        first_index.setOnClickListener(this);
        second_index.setOnClickListener(this);
        third_index.setOnClickListener(this);
        fourth_index.setOnClickListener(this);

    }

    /**
     * 点击事件
     */
    @Override
    public void onClick(View view) {
        int index = view.getId();

        switch (index) {

            /**
             * 点击首页按钮
             */
            case R.id.foot_first_index:
                clickFirst();
                break;

            /**
             * 点击众筹投资按钮
             */
            case R.id.foot_second_index:
                int i = SecondFragment.LABLE_ALL;
                Message message = handler.obtainMessage();
                message.obj = i;
                handler.handleMessage(message);
                clickSecond();
                break;

            /**
             * 点击排行榜按钮
             */
            case R.id.foot_third_index:
                clickThird();
                break;

            /**
             * 点击我的按钮
             */
            case R.id.foot_fourth_index:
                if (isLogin()) {
                clickFourth();
                }
                break;
        }
    }

    /**
     * 点击首页按钮
     */
    private void clickFirst() {
        search.setVisibility(View.VISIBLE);
        logo.setVisibility(View.VISIBLE);
        title.setVisibility(View.GONE);
        FragmentTransaction transaction = manager.beginTransaction();
        setFalse();
        foot_first_pic.setSelected(true);
        foot_first_text.setTextColor(Color.parseColor("#e9a150"));

        hideFragment(transaction);

        if (firstFragment == null) {
            firstFragment = new FirstFragment();
            transaction.add(R.id.fragment_framelayout, firstFragment);
        } else {
            transaction.show(firstFragment);
            firstFragment.removeFocus();
        }
        transaction.commit();
    }

    /**
     * 点击排行榜按钮
     */
    private void clickThird() {
        search.setVisibility(View.INVISIBLE);
        title.setText("排行榜");
        title.setVisibility(View.VISIBLE);
        logo.setVisibility(View.GONE);
        FragmentTransaction transaction = manager.beginTransaction();

        setFalse();
        foot_third_pic.setSelected(true);
        foot_third_text.setTextColor(Color.parseColor("#e9a150"));

        hideFragment(transaction);

        if (thirdFragment == null) {
            thirdFragment = new ThirdFragment();
            transaction.add(R.id.fragment_framelayout, thirdFragment);
        } else {
            transaction.show(thirdFragment);
        }
        transaction.commit();
    }

    /**
     * 跳转到我的页面
     */
    private void clickFourth() {
        search.setVisibility(View.VISIBLE);
        title.setText("我的");
        title.setVisibility(View.VISIBLE);
        logo.setVisibility(View.GONE);
        FragmentTransaction transaction = manager.beginTransaction();
        setFalse();
        foot_fourth_pic.setSelected(true);
        foot_fourth_text.setTextColor(Color.parseColor("#e9a150"));

        hideFragment(transaction);

        if (fourthFragment == null) {
            fourthFragment = new FourthFragment();
            transaction.add(R.id.fragment_framelayout, fourthFragment);
        } else {
            transaction.show(fourthFragment);
        }
        transaction.commit();
    }

    /**
     * 点击众筹投资按钮
     */
    public void clickSecond() {

        search.setVisibility(View.VISIBLE);
        title.setText("众筹投资");
        title.setVisibility(View.VISIBLE);
        logo.setVisibility(View.GONE);
        FragmentTransaction transaction = manager.beginTransaction();

        setFalse();
        foot_second_pic.setSelected(true);
        foot_second_text.setTextColor(Color.parseColor("#e9a150"));

        hideFragment(transaction);

        if (secondFragment == null) {
            secondFragment = new SecondFragment();
            transaction.add(R.id.fragment_framelayout, secondFragment);
        } else {
            transaction.show(secondFragment);
        }
        transaction.commit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == 1) {
            //若登陆成功则跳转到我的页面
            clickFourth();
        }
        if (requestCode == 1 && resultCode ==2){
            Log.d(TAG,"退出成功！");
            clickFirst();
        }
    }

    /**
     * 判断是否登陆
     * @return 若已经登陆返回true
     */
    private boolean isLogin() {
        boolean flag = false;
        boolean isLogin = mSharedPreferences.getBoolean("isLogin", false);
        if (!isLogin) {
            startActivityForResult(new Intent(HomeActivity.this, LoginActivity.class), 0);
        } else
            flag = isLogin;
        return flag;
    }

    /**
     * 隐藏所有Fragment
     *
     * @param transaction 每次都需要开启一个事物来实现
     */
    private void hideFragment(FragmentTransaction transaction) {
        if (firstFragment != null) {
            transaction.hide(firstFragment);
        }
        if (secondFragment != null) {
            transaction.hide(secondFragment);
        }
        if (thirdFragment != null) {
            transaction.hide(thirdFragment);
        }
        if (fourthFragment != null) {
            transaction.hide(fourthFragment);
        }
    }

    private void setFalse() {
        int size = foots.size();
        for (int i = 0; i < size; i++) {
            foots.get(i).setSelected(false);
            foot_texts.get(i).setTextColor(Color.parseColor("#545454"));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
//                BaseApplication.dbAddressController.closeDB();
//                BaseApplication.dbUserInfoController.closeDB();
//                BaseApplication.dbIndexController.closeDB();
                BaseApplication.INSTANCE.AppExit(getApplicationContext());
                BaseApplication.imageLoader.close();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 注册广播接收器接收在主页中选择的类别
     */

    public class ChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle extras = intent.getExtras();
            int lable = extras.getInt("lable");
            Message message = handler.obtainMessage();
            message.obj = lable;
            handler.handleMessage(message);
        }
    }
}
